#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QFileDialog>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_button_Read_clicked()
{
    QString path = QFileDialog::getOpenFileName(this,"open","../","TXT(*.txt)");

    if(path.isEmpty() == false)
    {
        QFile file(path);
        //打开 只读方式
        bool isOK = file.open(QIODevice::ReadOnly);
        if(isOK == true)
        {
            //读文件 显示到窗口 默认utf8
            QByteArray array = file.readAll();
            //显示到编辑区
            ui->textEdit->setText(array);
            file.close();
        }
    }
}

void Widget::on_button_Write_clicked()
{
    //选择保存路径
    QString path = QFileDialog::getSaveFileName(this,"save","../","txt(*.txt)");
    if(path.isEmpty() == false)
    {
        QFile file;//创建文件对象
        //关联文件名字
        file.setFileName(path);

        bool isok = file.open(QIODevice::WriteOnly);
        if(isok)
        {
            QString str = ui->textEdit->toPlainText();
            //QString -> QByteArray
            file.write(str.toUtf8());
            file.close();
        }

    }
}
